package com.ali.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
//        buffer();
        copiedBuffer();
    }

    private static void buffer() {
        //构建缓冲区，长度为10
        ByteBuf byteBuf = Unpooled.buffer(5);
        for (int i = 1; i <= 5; i++) {
            //获取写入下标
            System.out.println("beforeWriterIndex：" + byteBuf.writerIndex());
            //写入内容
            byteBuf.writeByte(i);
            //获取写入下标
            System.out.println("afterWriterIndex：" + byteBuf.writerIndex());
        }
        //获取缓冲区长度
        System.out.println("capacity：" + byteBuf.capacity());
        //获取可读取的字节数
        for (int i = 0; i < byteBuf.readableBytes(); i++) {
            //根据下标获取内容
            System.out.println(byteBuf.getByte(i));
        }
        //获取可读取的字节数
        for (int i = 0; i < byteBuf.readableBytes(); i++) {
            //获取读取下标
            System.out.println("beforeReaderIndex：" + byteBuf.readerIndex());
            //读取内容
            System.out.println(byteBuf.readByte());
            //获取读取下标
            System.out.println("afterReaderIndex：" + byteBuf.readerIndex());
        }
    }

    private static void copiedBuffer() {
        //构建缓冲区
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello world", StandardCharsets.UTF_8);
        //获取内容
        System.out.println(byteBuf.toString(StandardCharsets.UTF_8));
        //获取部分内容
        System.out.println(byteBuf.getCharSequence(0, 4, StandardCharsets.UTF_8));
        //是否包含字节数组
        if (byteBuf.hasArray()) {
            //获取字节数组
            byte[] bytes = byteBuf.array();
            System.out.println(new String(bytes, StandardCharsets.UTF_8));
        }
    }
}
